<?php
	namespace app\index\controller;

	use \think\Db;

	use think\Session;

	class Ticket extends Base{

		public function search(){

			try{

				if($this->method=='post'){

					$departCity=input('post.departCity');

					$destination=input('post.destination');

					$departDate=input('post.departDate');

					if($departCity=='' || $destination=='' || $departDate==''){
						return $this->fail('缺少参数~');
					}

					$startTime=time();

					$endTime=$startTime+60*60*24;

					$row=Db::name('ticket')->where(['t_departCity'=>$departCity,'t_destination'=>$destination,'t_time'=>['>=',$startTime,'<=',$endTime]])->select();

					return $this->success($row);

				}else{

					echo "拒绝访问";

				}

			}catch(\Exception $e){

				return $this->err($e);

			}

		}

		public function details(){

			try{

				if($this->method=='post'){

					$id=(int)input('post.id');

					$time=time();

					$row=Db::name('ticket')->where(['t_id'=>$id,'t_time'=>['>=',$time]])->find();

					if(!$row){

						return $this->fail('该车票不存在或已过期');

					}

					return $this->success($row);

				}else{

					echo '拒绝访问';

				}

			}catch(\Exception $e){

				return $this->err($e);

			}

		}

		public function purchase(){

			try{

				if($this->method=='post'){

					$user=Session::get('userInfo');

					if(!$user){

						return $this->fail('请先登录后，在操作~',-1);

					}

					$id=(int)input('post.id');

					$seat=(int)input('post.seat');

					$time=time();

					$row=Db::name('ticket')->where(['t_id'=>$id,'t_time'=>['>=',$time]])->find();

					if(!$row){

						return $this->fail('该车票不存在或已过期');

					}

					if(empty($row['t_seat'][$seat]) || $row['t_seat'][$seat]['count']<=0 ){

						return $this->fail('该车票已被抢光~');

					}

					$user=Db::name('user')->where(['u_id'=>$user['id']])->find();

					if($user['u_money']<$row['t_seat'][$seat]['pric']){

						return $this->fail('你的余额不足~');

					}

					$money=0-$row['t_seat'][$seat]['pric'];

					// die('t_seat.'.$seat.'.count');

					$res=Db::name('user')->where(['u_id'=>$user['u_id']])->setInc('u_money',$money);

					$res2=Db::name('ticket')->where(['t_id'=>$id,'t_seat.'.$seat.'.count'=>['>',0]])->setInc('t_seat.'.$seat.'.count',-1);

					if($res && $res2){

						return $this->success();

					}

					return $this->fail('订购失败~');

				}else{

					echo '拒绝访问';

				}

			}catch(\Exception $e){

				return $this->err($e);

			}

		}

	}
?>